<!doctype html>
<html>
<head>
<meta charset="UTF-8">
    <title>动态表单</title>
    <script src="http://cdn.staticfile.org/jquery/1.3.0/jquery.min.js"></script>
  
    <script type="text/javascript">
        $(document).ready(function() {
            $('#btnAdd').click(function() {
                var num     = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
                var newNum  = new Number(num + 1);      // the numeric ID of the new input field being added
  
                // create the new element via clone(), and manipulate it's ID using newNum value
                var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
  
                // manipulate the name/id values of the input inside the new element
               //  newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
                 
                newElem.children(':first').attr('id', 'user['+ newNum + ']name' ).attr('name', 'user['+ newNum + ']name' );
                 
                newElem.children(':next').attr('id', 'user['+ newNum + ']age' ).attr('name', 'user['+ newNum + ']age' );
                newElem.children(':last').attr('id', 'user['+ newNum + ']gender' ).attr('name', 'user['+ newNum + ']gender' );
                 
                  
                // insert the new element after the last "duplicatable" input field
                $('#input' + num).after(newElem);
  
                // enable the "remove" button
                $('#btnDel').attr('disabled','');
  
                // business rule: you can only add 5 names
                if (newNum == 5)
                    $('#btnAdd').attr('disabled','disabled');
            });
  
            $('#btnDel').click(function() {
                var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
                $('#input' + num).remove();     // remove the last element
  
                // enable the "add" button
                $('#btnAdd').attr('disabled','');
  
                // if only one element remains, disable the "remove" button
                if (num-1 == 1)
                    $('#btnDel').attr('disabled','disabled');
            });
  
            $('#btnDel').attr('disabled','disabled');
        });
    </script>
</head>
  
<body>
  
<form id="myForm" action="b.php" method="post">
    <div id="input1" style="margin-bottom:4px;" class="clonedInput">
       姓名: <input type="text" name="user[1]name" id="user[1]name" />
       年龄: <input type="text" name="user[1]age" id="user[1]age" />
       性别: <input type="text" name="user[1]gender" id="user[1]gender" />
    </div>
    </div>
  
    <div>
        <input type="button" id="btnAdd" value="添加用户" />
        <input type="button" id="btnDel" value="删除用户" />
        <input type="submit">
    </div>
</form>
  
</body>
</html>
